/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2018-12-15 Time: 23:16
 *
 * 新建报修工单
 */

import React, {Component} from 'react';
import {
    SafeAreaView,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    Modal, FlatList,
} from 'react-native';
import {connect} from 'react-redux';
import {
    COLOR_GRAY_BACKGROUND, COLOR_GRAY_LINE, COLOR_THEME, FONT_COLOR_SUB_TITLE
} from "../../../../constant/PHColors"
import {styles} from "../DepartmentalRepairOrderScreen/DepartmentalRepairOrderScreen.Style";
import {Header} from "react-navigation";
import {SCREEN_WIDTH} from "../../../../constant/PHScreen";
import {getDs,getStatus,getRole,getArea} from "./Actions"
import {FetchStatus} from "../../../../configuration/RequestConfiguration";
import {ReturnStatus} from "../../../../configuration/ReturnStatus";
import User from "../../../../model/User/User";

class DepartmentalRepairOrderScreen extends Component {

    static navigationOptions = ({navigation}) => ({
        title: '部门报修单'
    })

    //构造
    constructor(props) {
        super(props);



        this.showSelect1 = this.showSelect1.bind(this);
        this.showSelect2 = this.showSelect2.bind(this);
        this.showSelect3 = this.showSelect3.bind(this);
        this.changeSelect = this.changeSelect.bind(this);
        this.state = {
            modalStatus: false,
            modalFloor: false,
            modalGroup: false,
            selectStatusText: "全部状态",
            selectAreaText: "全部楼层",
            selectRoleText: "全部工种",
            defaultMsg:[],
            selectStatus:[],
            selectRole:[],
            selectArea:[],
            selectValue:{"status":"","role":"","area":"","work_userid":""},
            showFoot:0, // 控制foot， 0：隐藏footer  1：已加载完成,没有更多数据   2 ：显示加载中
            pageNo: 1,//当前第几页
            totalPage:0,//总的页数
            itemNo:20,//item的个数
            recordNum:0,//数据总条数
            refreshing:false,//下拉刷新
        };


    }

    componentWillReceiveProps(nextProps, nextContext): void {
        let {dispatch} = this.props;

        if (nextProps.onGetDs !== this.props.onGetDs && nextProps.onGetDs.fetchStatus === FetchStatus.Success) {
            let defaultInfo = nextProps.onGetDs.rows;
            this.state.showFoot = 0;
            if(this.state.pageNo>=nextProps.onGetDs.total){
                this.state.showFoot = 1;//listView底部显示没有更多数据了
            }
            if(this.state.pageNo===1){
                defaultInfo = nextProps.onGetDs.rows
            }else{
                defaultInfo = this.state.defaultMsg.concat(defaultInfo)
            }
            this.setState({
                defaultMsg: defaultInfo,
                totalPage:nextProps.onGetDs.total,
                recordNum:nextProps.onGetDs.records,
                itemNo:20,//item的个数
                refreshing:false,
            });
        }

        //状态
        if (nextProps.onDepartRepairOrderGetStatus !== this.props.onDepartRepairOrderGetStatus && nextProps.onDepartRepairOrderGetStatus.fetchStatus === FetchStatus.Success) {
            if (nextProps.onDepartRepairOrderGetStatus.RETURN === ReturnStatus.Success) {
                let selectStatus = nextProps.onDepartRepairOrderGetStatus.DATA;
                this.setState({
                    selectStatus: selectStatus
                });
                // console.log("222222-----------------"+JSON.stringify(nextProps.onDepartRepairOrderGetStatus.DATA))
            } else {

            }
        }

        //工种
        if (nextProps.onDepartRepairOrderGetRole !== this.props.onDepartRepairOrderGetRole && nextProps.onDepartRepairOrderGetRole.fetchStatus === FetchStatus.Success) {
            if (nextProps.onDepartRepairOrderGetRole.RETURN === ReturnStatus.Success) {
                let selectRole = nextProps.onDepartRepairOrderGetRole.DATA;
                this.setState({
                    selectRole: selectRole
                });
                // console.log("333333-----------------"+JSON.stringify(nextProps.onDepartRepairOrderGetRole.DATA))
            } else {

            }
        }

        //区域
        if (nextProps.onDepartRepairOrderGetArea !== this.props.onDepartRepairOrderGetArea && nextProps.onDepartRepairOrderGetArea.fetchStatus === FetchStatus.Success) {
            if (nextProps.onDepartRepairOrderGetArea.RETURN === ReturnStatus.Success) {
                let selectArea = nextProps.onDepartRepairOrderGetArea.DATA;
                this.setState({
                    selectArea: selectArea
                });
                // console.log("44444-----------------"+JSON.stringify(nextProps.onDepartRepairOrderGetArea.DATA))
            } else {

            }
        }
    }

    // 组件渲染后调用
    componentDidMount() {
        this.setState({
            pageNo:1,
        });

        let {dispatch} = this.props;

        User.getUser(user => {
            if (user&&user.token) {
                this.state.selectValue.work_userid = user.userid;
                let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};

                dispatch(getStatus());

                dispatch(getRole());

                dispatch(getArea());

                dispatch(getDs(JSON.stringify(str),this.state.pageNo));
            }
        })
        // this.props.navigation.navigate('MainNavigator');


    }

    render(){
        return (
            <SafeAreaView style={styles.body}>

                <View style={styles.body}>
                    {this.selectTitle()}
                    <View style={styles.headerContainer}>
                        <Text style={styles.headerText}>
                            共{this.state.recordNum?this.state.recordNum:'0'}张单
                        </Text>
                    </View>
                    <FlatList
                        data = {this.state.defaultMsg}
                        onRefresh = {this._onRefresh.bind(this)} //刷新操作
                        refreshing = {this.state.refreshing}
                        renderItem={this._renderItem}
                        ListFooterComponent={this._renderFooter.bind(this)}
                        onEndReachedThreshold={0.1}
                        keyExtractor={(item, index) => index.toString()}
                        onEndReached={this._onEndReached.bind(this)}
                    />
                </View>

                <Modal
                    visible={this.state.modalStatus}
                    //显示是的动画默认none
                    //从下面向上滑动slide
                    //慢慢显示fade
                    animationType = {'none'}
                    //是否透明默认是不透明 false
                    transparent = {true}
                    //关闭时调用
                    onRequestClose={()=> this.onRequestClose()}
                >
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={this.showSelect1}>
                        <View style={styles.modalContainer}>
                            {this.selectTitle()}
                            <View style={{width:SCREEN_WIDTH, backgroundColor:COLOR_GRAY_BACKGROUND,flexDirection: 'row',flexWrap: 'wrap',}} >
                                <View style={styles.selectTop}>
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.state.selectStatusText = '全部状态';
                                        this.state.selectValue.status = '';
                                        this.changeSelect()
                                    }}>
                                        <View style={styles.selectTopBox}>
                                            <View style={styles.cellRight}>
                                                <View style={styles.cellRightTop}>
                                                    <Text style={styles.cellTitleText}>
                                                        全部状态
                                                    </Text>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                                {
                                    this.state.selectStatus.map((item, index) => {
                                        return this._renderStatus(item, index)
                                    })
                                }
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>

                <Modal visible={this.state.modalFloor} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={this.showSelect2}>
                        <View style={styles.modalContainer}>
                            {this.selectTitle()}
                            <View style={{ width:SCREEN_WIDTH,  backgroundColor:COLOR_GRAY_BACKGROUND,flexDirection: 'row',flexWrap: 'wrap',}} >
                                <View style={styles.selectTop}>
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.state.selectAreaText = '全部楼层';
                                        this.state.selectValue.area = '';
                                        this.changeSelect()
                                    }}>
                                        <View style={styles.selectTopBox}>
                                            <View style={styles.cellRight}>
                                                <View style={styles.cellRightTop}>
                                                    <Text style={styles.cellTitleText}>
                                                        全部楼层
                                                    </Text>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                                {
                                    this.state.selectArea.map((item, index) => {
                                        return this._renderArea(item, index)
                                    })
                                }
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>

                <Modal visible={this.state.modalGroup} animationType = {'none'} transparent = {true} onRequestClose={()=> this.onRequestClose()} >
                    <TouchableOpacity style={{flex: 1}} activeOpacity={1} onPress={this.showSelect3}>
                        <View style={styles.modalContainer}>
                            {this.selectTitle()}
                            <View style={{width:SCREEN_WIDTH, backgroundColor:COLOR_GRAY_BACKGROUND,flexDirection: 'row',flexWrap: 'wrap',}} >
                                <View style={styles.selectTop}>
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.state.selectRoleText = '全部工种';
                                        this.state.selectValue.role = '';
                                        this.changeSelect()
                                    }}>
                                        <View style={styles.selectTopBox}>
                                            <View style={styles.cellRight}>
                                                <View style={styles.cellRightTop}>
                                                    <Text style={styles.cellTitleText}>
                                                        全部工种
                                                    </Text>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                    <TouchableOpacity activeOpacity={0.8} onPress={()=>{
                                        this.state.selectRoleText = '我创建的';
                                        this.state.selectValue.role = '';
                                        this.changeSelect()
                                    }}>
                                        <View style={styles.selectTopBox}>
                                            <View style={styles.cellRight}>
                                                <View style={styles.cellRightTop}>
                                                    <Text style={styles.cellTitleText}>
                                                        我创建的
                                                    </Text>
                                                </View>
                                            </View>
                                        </View>
                                    </TouchableOpacity>
                                </View>
                                {
                                    this.state.selectRole.map((item, index) => {
                                        return this._renderRole(item, index)
                                    })
                                }
                            </View>
                        </View>
                    </TouchableOpacity>
                </Modal>

            </SafeAreaView>
        )
    }

    //下拉刷新,更改状态，重新获取数据
    _onRefresh(){
        this.setState({
            refreshing:true,
            defaultMsg:[]
        },()=>{
            this.state.pageNo=1;
            let {dispatch} = this.props;
            let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};
            dispatch(getDs(JSON.stringify(str),this.state.pageNo))
        });
    }

    _onEndReached(){
        //如果是正在加载中或没有更多数据了，则返回
        if(this.state.showFoot !== 0 ){
            return ;
        }
        //如果当前页大于或等于总页数，那就是到最后一页了，返回
        if((this.state.pageNo!==1) && (this.state.pageNo>=this.state.totalPage)){
            return;
        } else {
            this.state.pageNo++;
        }
        //底部显示正在加载更多数据
        this.state.showFoot=2;

        //获取数据
        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};
        dispatch(getDs(JSON.stringify(str),this.state.pageNo))
    }

    _renderFooter(){
        if (this.state.showFoot === 1) {
            return (
                <View style={{height:30,alignItems:'center',justifyContent:'flex-start',}}>
                    <Text style={{color:'#999999',fontSize:14,marginTop:5,marginBottom:5,}}>
                        没有更多数据了
                    </Text>
                </View>
            );
        } else if(this.state.showFoot === 2) {
            return (
                <View style={styles.footer}>
                    {/*<ActivityIndicator />*/}
                    <Text>正在加载更多数据...</Text>
                </View>
            );
        } else if(this.state.showFoot === 0){
            return (
                <View style={styles.footer}>
                    <Text></Text>
                </View>
            );
        }
    }

    onRequestClose(){
        this.setState({
            modalStatus: false,
            modalFloor: false,
            modalGroup: false,
        })
    }

    //筛选条件点击
    showSelect1(){
         this.setState({
             modalFloor: false,
             modalGroup: false,
             modalStatus: !this.state.modalStatus,

         })
    }

    showSelect2(){
        this.setState({
            modalStatus: false,
            modalGroup: false,
            modalFloor: !this.state.modalFloor,

        })
    }

    showSelect3(){
        this.setState({
            modalStatus: false,
            modalFloor: false,
            modalGroup: !this.state.modalGroup,

        })
    }

    changeSelect(){
        this.setState({
            modalStatus: false,
            modalFloor: false,
            modalGroup: false,
        });
        this.state.pageNo=1;

        let {dispatch} = this.props;
        let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":this.state.selectValue};
        dispatch(getDs(JSON.stringify(str),this.state.pageNo))
    }

    //筛选条件View
    selectTitle(){
        return (
            <View style={{flexDirection: 'row'}}>
                <TouchableOpacity activeOpacity={0.8} onPress={this.showSelect1}>
                    <View style={styles.cellBoxLeft}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text style={styles.cellTitleText}>
                                    {this.state.selectStatusText}
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity activeOpacity={0.8} onPress={this.showSelect2}>
                    <View style={styles.cellBoxCenter}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text style={styles.cellTitleText}>
                                    {this.state.selectAreaText}
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>

                <TouchableOpacity activeOpacity={0.8} onPress={this.showSelect3}>
                    <View style={styles.cellBoxRight}>
                        <View style={styles.cellRight}>
                            <View style={styles.cellRightTop}>
                                <Text style={styles.cellTitleText}>
                                    {this.state.selectRoleText}
                                </Text>
                            </View>
                        </View>
                    </View>
                </TouchableOpacity>
            </View>
        )
    }

    //列表内容循环
    _renderItem = ({ item }) => {
        let _this=this;
        return (
            <TouchableOpacity activeOpacity={0.8}  onPress={() => {
                this.props.navigation.navigate('DepartmentalRepairOrderDetailScreen',{"sn":item.sn,"beforePage":"DepartmentalRepairOrderScreen",callBack:()=>{
                    let {dispatch} = _this.props;
                    let str = {"arg":{"SQLfields":"sn,status,object_name,type,recordno,area_fullname,object_fullname,create_datetime,report_username,report_connect,remark"},"where":_this.state.selectValue};
                    dispatch(getDs(JSON.stringify(str),_this.state.pageNo))
                }})
            }}>
                <View style={styles.boxBody} onPress={()=>{

                }}>
                    <View style={styles.top}>
                        <View style={styles.topLeft}>
                            <Text style={styles.topPointText}>
                                {item.object_fullname ? (item.object_fullname.length > 10 ? item.object_fullname.substr(0, 10) + "..." : item.object_fullname) : ""}
                            </Text>
                        </View>
                        <View style={styles.topRight}>
                            {item.type==="紧急维修"?<Text style={styles.topFromTextRed}>{item.type}</Text>:<Text style={styles.topFromTextBlue}>{item.type}</Text>}
                        </View>
                    </View>

                    <View style={styles.center}>
                        <Text style={styles.centerText}>
                            {item.area_fullname ? (item.area_fullname.length > 17 ? item.area_fullname.substr(0, 17) + "..." : item.area_fullname) : ""}
                        </Text>
                    </View>

                    <View style={styles.bottom}>
                        <Text style={styles.bottomText}>
                            {item.create_datetime}
                        </Text>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    //状态循环
    _renderStatus(item, index){
        return(
            <TouchableOpacity key={index} activeOpacity={0.8} onPress={()=>{
                this.state.selectStatusText = item.STATUS
                this.state.selectValue.status = item.STATUS;
                this.changeSelect()
            }}>
                <View style={styles.cellBox}>
                    <View style={styles.cellRight}>
                        <View style={styles.cellRightTop}>
                            <Text style={styles.cellTitleText}>
                                {item.STATUS}
                            </Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    //工种循环
    _renderRole(item, index){
        return(
            <TouchableOpacity key={index} activeOpacity={0.8} onPress={()=>{
                this.state.selectRoleText = item.role
                this.state.selectValue.role = item.role;
                this.changeSelect()
            }}>
                <View style={styles.cellBox}>
                    <View style={styles.cellRight}>
                        <View style={styles.cellRightTop}>
                            <Text style={styles.cellTitleText}>
                                {item.role}
                            </Text>
                        </View>
                    </View>
                </View>
            </TouchableOpacity>
        )
    };

    _renderArea(item, index){
        if(item.level===1){
            return(
                <View key={index} style={styles.selectBox}>
                    <View style={{width: SCREEN_WIDTH,left:15,paddingBottom: 5,flexDirection: 'row',}}>
                        <Text style={styles.selectTopText}>
                            {item.name}
                        </Text>
                    </View>
                    <View style={styles.selectTop}>

                        <TouchableOpacity  activeOpacity={0.8} onPress={()=>{
                            this.state.selectAreaText = item.name;
                            this.state.selectValue.area = item.sn;
                            this.changeSelect()
                        }}>
                            <View style={styles.cellBox2}>
                                <View style={styles.cellRight}>
                                    <View style={styles.cellRightTop}>
                                        <Text style={styles.cellTitleText}>
                                            全部
                                        </Text>
                                    </View>
                                </View>
                            </View>
                        </TouchableOpacity>
                        {
                            this.state.selectArea.map((value, key) => {
                                if(value.level===2&&value.sn.split('.')[0]===item.sn){
                                    return(
                                        <TouchableOpacity key={key} activeOpacity={0.8} onPress={()=>{
                                            this.state.selectAreaText = value.name;
                                            this.state.selectValue.area = value.sn;
                                            this.changeSelect()
                                        }}>
                                            <View style={styles.cellBox2}>
                                                <View style={styles.cellRight}>
                                                    <View style={styles.cellRightTop}>
                                                        <Text style={styles.cellTitleText}>
                                                            {value.name}
                                                        </Text>
                                                    </View>
                                                </View>
                                            </View>
                                        </TouchableOpacity>
                                    )
                                }
                            })
                        }
                    </View>
                </View>

            )
        }
    }
}

const props = state => {
    return {
        onGetDs: state.onGetDs,
        onDepartRepairOrderGetStatus: state.onDepartRepairOrderGetStatus,
        onDepartRepairOrderGetRole:state.onDepartRepairOrderGetRole,
        onDepartRepairOrderGetArea:state.onDepartRepairOrderGetArea,
    }
};

export default DepartmentalRepairOrderScreen = connect(props)(DepartmentalRepairOrderScreen);
